import { showModal, showToast } from "../../utils/asyncWx.js";
import regeneratorRuntime from '../../lib/runtime/runtime';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: {},
    cart: [],
    allChecked: false,
    totalPrice: 0,
    totalNum: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },
  setCart(cart) {
    let allChecked = cart.length ? cart.every(v => v.checked) : false
    let totalPrice = 0
    let totalNum = 0
    cart.forEach(v => {
      if (v.checked) {
        totalPrice += v.num * v.goods_price
        totalNum += v.num
      }
    });
    this.setData({ cart, allChecked, totalPrice, totalNum })
    wx.setStorageSync("cart", cart);
  },
  onShow() {
    let address = wx.getStorageSync("address");
    let cart = wx.getStorageSync("cart") || [];
    this.setCart(cart)
    this.setData({ address })
  },
  handleAddress() {
    wx.chooseAddress({
      success: (result) => {
        wx.setStorageSync("address", result);
      },
      fail: () => { },
      complete: () => { }
    });
  },
  handleChecked(e) {
    const goods_id = e.currentTarget.dataset.id
    let { cart } = this.data
    let index = cart.findIndex(v => v.goods_id === goods_id)
    cart[index].checked = !cart[index].checked
    this.setCart(cart)
  },
  handleItemAllCheck() {
    let { allChecked, cart } = this.data
    allChecked = !allChecked
    cart.forEach(v => v.checked = allChecked)
    this.setCart(cart)
  },
  async handleItemNumEdit(e) {
    let { operation, id } = e.currentTarget.dataset;
    let { cart } = this.data;
    let index = cart.findIndex(v => v.goods_id === id);
    if (cart[index].num === 1 && operation === -1) {
      const res = await showModal({ content: "您是否要删除？" });
      if (res.confirm) {
        cart.splice(index, 1);
        this.setCart(cart);
      }
    } else {
      cart[index].num += operation;
      this.setCart(cart);
    }
  },
  async handlePay() {
    let {address,totalNum}=this.data;
    if(!address.userName){
      await showToast({title:"您还没有选择收货地址"});
      return;
    }
    if(totalNum===0){
      await showToast({title:"您还没有选购商品"});
      return ;
    }
    wx.navigateTo({
      url: '/pages/pay/index'
    });
  }
})